package Arrays;

import java.util.Arrays;

/**
 * 作者:hfj
 * 功能:217.存在重复元素
 * 日期: 2025/10/28 9:57
 */
public class ContainsDuplicate {
    public static void main(String[] args) {
        int[] nums = {1,1,1,3,3,4,3,2,4,2};
        System.out.println(containsDuplicate1(nums));
    }

    //存在负数,不能用hash表
    public static boolean containsDuplicate1(int[] nums) {
        int[] hash = new int[nums.length+10];
        for (int i = 0; i < nums.length; i++) {
            hash[nums[i]]++;
            if (hash[nums[i]] == 2){
                return true;
            }
        }
        return false;
    }

    //超出时间异常
    public static boolean containsDuplicate2(int[] nums){
        for (int i = 0; i < nums.length; i++) {
            for (int j = i+1; j < nums.length; j++) {
                if (nums[i] == nums[j]){
                    return true;
                }
            }
        }
        return false;
    }

    //先排序,相邻的元素相邻
    public static boolean containsDuplicate(int[] nums){
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] == nums[i+1]){
                return true;
            }
        }
        return false;
    }
}
